package com.zzptc.lzh.myapp12;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zzptc.lzh.myapp12.Bean.User;

import org.litepal.LitePal;

import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private EditText yhm,mm;
    private Button dl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        getUser();
        setListener();
    }

    private void setListener() {
        dl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=yhm.getText().toString().trim();
                String psd=mm.getText().toString().trim();
                User user=confirmUser(usn,psd);
                if (user==null){
                    //登陆失败
                }else {
                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("myid",user.getId());
                    editor.putString("myname",user.getName());
                    editor.putInt("myimg",user.getUserimg());
                    editor.apply();
                    startActivity(intent);
                }
            }
        });
    }
    private User confirmUser(String usn,String psd){
        List<User> userList= LitePal.findAll(User.class);//litepal取数据，放在集合里
        for (User u:userList){
            if (usn.equals(u.getName())&&psd.equals(u.getPassword())){
                return u;
            }
        }
        return null;
    }

    private void getUser() {
        User user=new User(0,"张三","123");
        User user1=new User(0,"李四","456");
        User user2=new User(0,"王五","789");
        user.save();
        user1.save();
        user2.save();
    }

    private void initView() {
        yhm=findViewById(R.id.yhm);
        mm=findViewById(R.id.mm);
        dl=findViewById(R.id.dl);
    }

}
